// import { RootState } from '@/types/store'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
// import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import {
  getUserProfile,
  updateUserPhoto,
  updateUserProfile,
} from '@/store/actions/profile'
import styles from './index.module.scss'
import { useInitialState } from '@/utils/hooks'
import { useRef, useState } from 'react'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import dayjs from 'dayjs'
import { useHistory } from 'react-router-dom'
import { logout } from '@/store/actions/login'
const Item = List.Item

const ProfileEdit = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [showInupt, setShowInput] = useState<{
    visible: boolean
    type: '' | 'name' | 'intro'
  }>({ visible: false, type: '' })

  type ListState = {
    visible: boolean
    type: '' | 'gender' | 'photo'
  }
  const [showList, setShowList] = useState<ListState>({
    visible: false,
    type: '',
  })
  // 关闭弹层性别
  const hideList = () => {
    setShowList({
      type: '',
      visible: false,
    })
  }
  // 关闭弹层
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false,
    })
  }
  // 提交
  const fileRef = useRef<HTMLInputElement>(null)
  const onUpdate = async (type: string, value: string) => {
    // console.log({ [key]: value })
    // await dispatch(updateUserProfile({ [key]: value }))
    if (type === 'photo') {
      // 修改头像
      fileRef.current?.click()
      // console.log(fileRef.current)

      return
    }
    await dispatch(updateUserProfile(type, value))
    // 提示修改成功
    Toast.show({
      content: '修改成功',
      icon: 'success',
    })
    hideInput()
    hideList()
  }

  // const ProfileEdit = () => {
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    // console.log(file)
    const fd = new FormData()
    fd.append('photo', file)
    // console.log('fd', fd)
    // 发送请求
    await dispatch(updateUserPhoto(fd))
    Toast.show({
      icon: 'success',
      content: '修改头像成功',
    })
    hideList()
  }
  // 日期选择器
  const [showBirthday, setShowBirthday] = useState(false)

  const onBirthdayShow = () => {
    setShowBirthday(true)
  }
  const onBirthdayHide = () => {
    setShowBirthday(false)
  }
  // 推出
  const logoutFn = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗',
      onConfirm() {
        // 点击了确定按钮
        // 1. 清除token
        dispatch(logout())
        // 2. 跳转到登录页
        history.push('/login')
      },
    })
  }
  // }
  // 获取数据
  const { userProfile } = useInitialState(getUserProfile, 'profile')

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => {
                setShowList({
                  visible: true,
                  type: 'photo',
                })
              }}
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() =>
                setShowInput({
                  visible: true,
                  type: 'name',
                })
              }
            >
              昵称
            </Item>
            <Item
              arrow
              onClick={() =>
                setShowInput({
                  visible: true,
                  type: 'intro',
                })
              }
              extra={
                <span
                  className={classNames('intro', userProfile.intro && 'normal')}
                >
                  {userProfile.intro || '未填写'}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              onClick={() => setShowList({ visible: true, type: 'gender' })}
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
            >
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onBirthdayShow}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            value={new Date(userProfile.birthday)}
            onClose={onBirthdayHide}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onConfirm={(val) => {
              onUpdate('birthday', dayjs(val).format('YYYY-MM-DD'))
            }}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logoutFn}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改昵称 */}
      <Popup
        visible={showInupt.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
        destroyOnClose
      >
        <EditInput
          onUpdate={onUpdate}
          hideInput={hideInput}
          type={showInupt.type}
        ></EditInput>
      </Popup>
      {/* 修改性别 */}
      <Popup visible={showList.visible} position="bottom" destroyOnClose>
        <EditList
          onUpdate={onUpdate}
          type={showList.type}
          hideList={hideList}
        ></EditList>
      </Popup>
      <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
    </div>
  )
}

export default ProfileEdit
